#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<set>
using namespace std;

class B
{
public:
	B(){}
	B(int n,int s,vector<string>& vs, vector<vector<int>>& vvi):node_num(n),side_num(s),vs(vs),vvi(vvi){}

	~B(){}
	
	void makearr()
	{
		for (int i = 0; i < side_num; i++)
		{
			vector<string> tmp(2);
			cin >> tmp[0] >> tmp[1];
			int row = 0, col = 0;
			for (int i = 0; i < node_num; i++)
			{
				if (vs[i] == tmp[0])
				{
					row = i;
				}
				if (vs[i] == tmp[1])
				{
					col = i;
				}
			}
			vvi[row][col] = 1;
			vvi[col][row] = 1;
		}
	}

	void DFS(int n)
	{
		visited.insert(n);

		for (int i = 0; i < node_num; ++i) 
		{
			if (vvi[n][i] == 1 && visited.find(i) == visited.end()) 
			{
				DFS(i);
			}
		}
	}

	int numofcnt()
	{
		int count = 0;

		for (int i = 0; i < node_num; ++i) 
		{
			if (visited.find(i) == visited.end()) 
			{
				DFS(i);
				++count;
			}
		}

		return count;
	}

	void print()
	{
		makearr();
		int ret = numofcnt();
		for (auto& e : vs)
		{
			cout << e << " ";
		}
		cout << endl;
		for (auto& e : vvi)
		{
			for (auto& f : e)
			{
				cout << f << " ";
			}
			cout << endl;
		}
		cout << ret;
	}
		
private:
	int node_num, side_num;
	vector<string> vs;
	vector<vector<int>> vvi;
	set<int> visited;
};

void test2()
{
	int t;
	cin >> t;
	while (t--)
	{
		int node_num, side_num;
		cin >> node_num;
		vector<string> vs(node_num);
		vector<vector<int>> vvi(node_num, vector<int>(node_num));
		for (auto& e : vs)
		{
			cin >> e;
		}

		//for (int i = 0; i < node_num; i++)
		//{
		//	vvi.resize(node_num);
		//	for (int j = 0; i < node_num; j++)
		//	{
		//		vvi[i][j] = 0;
		//	}
		//}

		cin >> side_num;

		B b(node_num, side_num, vs, vvi);
		b.print();

		if (t)
		{
			cout << endl << endl;
		}
	}
}

int main()
{
	test2();
	return 0;
}
